﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;
using CamstarAPI;
public partial class uMESResourceManagementForm : BaseForm, INormalReport
{
    const string QueryWhere = "uMESResourceManagementForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESResourceManagementBusiness bll = new uMESResourceManagementBusiness();
    
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：设备管理";
        master.strTitle = "设备管理";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        if (!IsPostBack)
        {
            //ShowStatusMessage("", true);
            Dictionary<string, string> para = new Dictionary<string, string>();
            BindFactory(para);
            BindTeamInfo(para);
            BindEmployeeInfo(para);
            BindVendor();
            BindResourceStatus();
            ClearMessage();
        }
    }

    #region 数据绑定

    /// <summary>
    /// 绑定分厂信息
    /// </summary>
    /// <param name="para"></param>
    protected void BindFactory(Dictionary<string,string> para)
    {
        DataTable dt = bll.GetFactoryInfo(para);
        ddlFactory.DataTextField = "factoryname";
        ddlFactory.DataValueField = "factoryid";
        ddlFactory.DataSource = dt;
        ddlFactory.DataBind();
        ddlFactory.Items.Insert(0,"");
    }

    /// <summary>
    /// 绑定班组信息
    /// </summary>
    /// <param name="para"></param>
    protected void BindTeamInfo(Dictionary<string, string> para)
    {
        DataTable dt = bll.GetTeamInfo(para);
        ddlTeam.DataTextField = "TeamName";
        ddlTeam.DataValueField = "TeamID";
        ddlTeam.DataSource = dt;
        ddlTeam.DataBind();
        ddlTeam.Items.Insert(0, "");
    }

    /// <summary>
    /// 绑定责任人信息
    /// </summary>
    /// <param name="para"></param>
    protected void BindEmployeeInfo(Dictionary<string, string> para)
    {
        DataTable dt = bll.GetEmployeeInfo(para);
        ddlPersonLiable.DataTextField = "fullname";
        ddlPersonLiable.DataValueField = "nameValue";
        ddlPersonLiable.DataSource = dt;
        ddlPersonLiable.DataBind();
        ddlPersonLiable.Items.Insert(0, "");
    }

    /// <summary>
    /// 绑定设备状态
    /// </summary>
    protected void BindResourceStatus()
    {
        DataTable dt = bll.GetResourceStatusInfo();
        ddlStatus.DataTextField = "resourcestatusname";
        ddlStatus.DataValueField = "resourcestatusname";
        ddlStatus.DataSource = dt;
        ddlStatus.DataBind();
        ddlStatus.Items.Insert(0, "");
    }

    /// <summary>
    /// 绑定供应商
    /// </summary>
    protected void BindVendor()
    {
        DataTable dt = bll.GetVendorInfo();
        ddlVendor.DataTextField = "vendorname";
        ddlVendor.DataValueField = "vendorid";
        ddlVendor.DataSource = dt;
        ddlVendor.DataBind();
        ddlVendor.Items.Insert(0, "");
    }
    #endregion

    #region 数据查询
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.txtCurrentPage.Text = "1";
        Dictionary<string, string> query = GetQuery();
        QueryData(query);
    }
    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ClearDispData();
        ResetQuery();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strSearchName = txtSearchName.Text.Trim();
        string strSearchNum = txtSearchNum.Text.Trim();
        string strSearchAsset = txtSearchAsset.Text.Trim();
 
        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("Description", strSearchName);//设备名称
        result.Add("ResourceName", strSearchNum);//设备编号
        result.Add("AssetNumber", strSearchAsset);//资产编号

        Session[QueryWhere] = result;
        return result;
    }

    public void QueryData(Dictionary<string, string> query)
    {
        ShowStatusMessage("", true);
        ClearDispData();
        uMESPagingDataDTO result = bll.GetSourceData(query, Convert.ToInt32(this.txtCurrentPage.Text), 10);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        this.txtTotalPage.Text = result.PageCount;
        if (result.RowCount == "0")
        {
            this.txtCurrentPage.Text = "0";
        }
        lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
        this.txtPage.Text = this.txtCurrentPage.Text;

       
    }

    protected void ClearDispData()
    {
        ShowStatusMessage("", true);
        txtNum.ReadOnly = false;
        txtName.Text = string.Empty;
        txtNum.Text = string.Empty;
        txtAssetNumber.Text = string.Empty;
        txtContact.Text = string.Empty;
        txtNotes.Text = string.Empty;
      
        if (ddlFactory.Items.Count>0)
        {
            ddlFactory.SelectedIndex = 0;
        }
        if (ddlTeam.Items.Count > 0)
        {
            ddlTeam.SelectedIndex = 0;
        }
        if (ddlPersonLiable.Items.Count > 0)
        {
            ddlPersonLiable.SelectedIndex = 0;
        }
        if (ddlStatus.Items.Count > 0)
        {
            ddlStatus.SelectedIndex = 0;
        }
        if (ddlVendor.Items.Count > 0)
        {
            ddlVendor.SelectedIndex = 0;
        }

    }

    public void ResetQuery()
    {
        ShowStatusMessage("", true);

        Session[QueryWhere] = "";
        txtSearchName.Text = string.Empty;
        txtSearchNum.Text = string.Empty;
        txtSearchAsset.Text = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }
    #endregion

    #region 分页按钮
    public void lbtnFirst_Click(object sender, EventArgs e)
    {
        this.txtCurrentPage.Text = "1";
        Dictionary<string, string> query = GetQuery();
        QueryData(query);
    }

    public void lbtnLast_Click(object sender, EventArgs e)
    {
        this.txtCurrentPage.Text = this.txtTotalPage.Text;
        Dictionary<string, string> query = GetQuery();
        QueryData(query);
    }
    public void lbtnPrev_Click(object sender, EventArgs e)
    {
        int currentPage = Convert.ToInt32(this.txtCurrentPage.Text);
        if (currentPage > 1)
        {
            currentPage = currentPage - 1;
        }
        this.txtCurrentPage.Text = currentPage.ToString();
        Dictionary<string, string> query = GetQuery();
        QueryData(query);
    }
    public void lbtnNext_Click(object sender, EventArgs e)
    {
        int currentPage = Convert.ToInt32(this.txtCurrentPage.Text);
        int totalPage = Convert.ToInt32(this.txtTotalPage.Text);
        if (currentPage < totalPage)
        {
            currentPage = currentPage + 1;
        }
        this.txtCurrentPage.Text = currentPage.ToString();
        Dictionary<string, string> query = GetQuery();
        QueryData(query);
    }

    public void btnGo_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(this.txtPage.Text) > 0 && Convert.ToInt32(this.txtPage.Text) <= Convert.ToInt32(this.txtTotalPage.Text))
        {
            this.txtCurrentPage.Text = this.txtPage.Text;
            Dictionary<string, string> query = GetQuery();
            QueryData(query);
        }
    }
    #endregion

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        //ClientScript.RegisterStartupScript(GetType(), "", strScript);
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

    }
    #endregion

    #region 清除提示信息
    protected void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"" + "" + "\", 'true');</script>";
        LiteralControl child = new LiteralControl(strScript);
        WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    #region 选中行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            txtNum.ReadOnly = true;
            txtName.Text = string.Empty;
            if (e.Row.Cells.FromKey("description").Value!=null)
            {
                txtName.Text = e.Row.Cells.FromKey("description").Text ;
            }
           
            txtNum.Text = string.Empty;
            if (e.Row.Cells.FromKey("resourcename").Value != null)
            {
                txtNum.Text = e.Row.Cells.FromKey("resourcename").Text;
            }

            txtAssetNumber.Text = string.Empty;
            if (e.Row.Cells.FromKey("assetnumber").Value != null)
            {
                txtAssetNumber.Text = e.Row.Cells.FromKey("assetnumber").Text;
            }

            txtContact.Text = string.Empty;
            if (e.Row.Cells.FromKey("contact").Value != null)
            {
                txtContact.Text = e.Row.Cells.FromKey("contact").Text;
            }

            txtNotes.Text = string.Empty;
            if (e.Row.Cells.FromKey("notes").Value != null)
            {
                txtNotes.Text = e.Row.Cells.FromKey("notes").Text;
            }

            if (e.Row.Cells.FromKey("factoryid").Value != null)
            {
                ddlFactory.SelectedValue = e.Row.Cells.FromKey("factoryid").Text;
            }
  
            if (e.Row.Cells.FromKey("teamid").Value != null)
            {
                ddlTeam.SelectedValue = e.Row.Cells.FromKey("teamid").Text;
            }

            if (e.Row.Cells.FromKey("nameValue").Value != null)
            {
                ddlPersonLiable.SelectedValue = e.Row.Cells.FromKey("nameValue").Text;
            }
 
            if (e.Row.Cells.FromKey("resourcestatusname").Value != null)
            {
                ddlStatus.SelectedValue = e.Row.Cells.FromKey("resourcestatusname").Text;
            }

            if (e.Row.Cells.FromKey("vendorid").Value != null)
            {
                ddlVendor.SelectedValue = e.Row.Cells.FromKey("vendorid").Text;
            }

        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    #endregion

    #region 保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            string strMessage = string.Empty;
            bool oResult;
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;

            if (activeRow == null)
            {
                oResult = SaveData(ref strMessage);
            }
            else
            {
                oResult = UpdateData(ref strMessage);
            }
   
            if (oResult == true)
            {
                btnSearch_Click(sender,e);
            }
            strMessage = strMessage.Replace('\"',' ').Replace('\n',' ');
            ShowStatusMessage(strMessage, oResult);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 保存设备信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <returns></returns>
    protected bool SaveData(ref string strMessage)
    {
        bool blResult = true;
        strMessage = string.Empty;
        if (txtNum.Text==null || txtNum.Text=="")
        {
            strMessage = "设备编号不能为空！";
            blResult = false;
            return blResult;
        }

        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
        //UltraGridRow activeRow1 = wgWorkFlow.DisplayLayout.ActiveRow;
        //UltraGridRow activeRow2 = wgSpec.DisplayLayout.ActiveRow;

        Dictionary<string, List<ClientAPIEntity>> p_ChildEntity = new Dictionary<string, List<ClientAPIEntity>>();
        var m_DataList = new List<ClientAPIEntity>();

        var dataEntity = new ClientAPIEntity();

        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
        dataEntity.ClientDataName = "Name";
        dataEntity.ClientDataValue = txtNum.Text;
        //dataEntity.ClientOtherValue = "";
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Description";
        dataEntity.ClientDataValue = txtName.Text;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "AssetNumber";
        dataEntity.ClientDataValue = txtAssetNumber.Text;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Factory";
        dataEntity.ClientDataValue = ddlFactory.SelectedItem.Text;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Team";
        dataEntity.ClientDataValue = ddlTeam.SelectedItem.Text;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
        m_DataList.Add(dataEntity);

        string strPersonliable = ddlPersonLiable.SelectedValue;
        string[] array = strPersonliable.Split('-');

        if (array.Length>0)
        {
            strPersonliable = array[0];
        }
        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Personliable";
        dataEntity.ClientDataValue = strPersonliable;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "ResourceStatus";
        dataEntity.ClientDataValue = ddlStatus.SelectedValue;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Vendor";
        dataEntity.ClientDataValue = ddlVendor.SelectedItem.Text;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.NamedObjectField;
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Contact";
        dataEntity.ClientDataValue = txtContact.Text;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField; ;
        m_DataList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Notes";
        dataEntity.ClientDataValue = txtNotes.Text;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField; ;
        m_DataList.Add(dataEntity);


        // p_ChildEntity.Add(0.ToString(), m_DataList);
        string strTxnDocName, strTxnName;
        strTxnDocName = "ResourceDoc";
        strTxnName = "Resource";
       
        string strApiUserName = userInfo["EmployeeName"];
        string strApiPassword = userInfo["Password"];
        var api = new CamstarClientAPI(strApiUserName, strApiPassword);
        blResult = api.CreateModel("ResourceMaint", m_DataList, null, ref strMessage);

        if (blResult==true)
        {
            strMessage = "保存成功！";
        }
        return blResult;
    }

    protected bool UpdateData(ref string strMessage)
    {
        bool blResult = true;
        strMessage = string.Empty;
        try
        {
            DataTable dtUpdate = new DataTable();
            dtUpdate.Columns.Add("TableName");
            dtUpdate.Columns.Add("ResourceName");
            dtUpdate.Columns.Add("Description");
            dtUpdate.Columns.Add("AssetNumber");
            dtUpdate.Columns.Add("FactoryId");
            dtUpdate.Columns.Add("TeamId");
            dtUpdate.Columns.Add("PersonLiableId");
            dtUpdate.Columns.Add("ResourceStatusId");
            dtUpdate.Columns.Add("VendorId");
            dtUpdate.Columns.Add("Contact");
            dtUpdate.Columns.Add("Notes");

            dtUpdate.Rows.Add();
            int intUpdateRow = dtUpdate.Rows.Count - 1;

            string strPersonliable = ddlPersonLiable.SelectedValue;
            string[] array = strPersonliable.Split('-');

            if (array.Length > 0)
            {
                strPersonliable = array[1];
            }
            dtUpdate.Rows[intUpdateRow]["TableName"] = "resourcedef";
            dtUpdate.Rows[intUpdateRow]["ResourceName"] = txtNum.Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["Description"] = txtName.Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["AssetNumber"] = txtAssetNumber.Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["FactoryId"] = ddlFactory.SelectedValue + "㊣String";
            dtUpdate.Rows[intUpdateRow]["TeamId"] = ddlTeam.SelectedValue + "㊣String";
            dtUpdate.Rows[intUpdateRow]["PersonLiableId"] = strPersonliable + "㊣String";
            dtUpdate.Rows[intUpdateRow]["ResourceStatusId"] = ddlStatus.SelectedValue + "㊣String";
            dtUpdate.Rows[intUpdateRow]["VendorId"] = ddlVendor.SelectedValue + "㊣String";
            dtUpdate.Rows[intUpdateRow]["Contact"] = txtContact.Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["Notes"] = txtNotes.Text + "㊣String";

            int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
            if (iResult == -1)
            {
                blResult = false;
              
            }

            return blResult; 
        }
        catch (Exception ex)
        {
            blResult = false;
            strMessage = ex.Message;
        }
        return blResult;

    }

    //验证是否是数字
    public bool IsNumeric(string s)
    {
        bool bReturn = true;
        double result = 0;
        try
        {
            result = double.Parse(s);
        }
        catch
        {
            result = 0;
            bReturn = false;
        }
        return bReturn;
    }

    //验证是否是正整数
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }
    #endregion

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            ClearDispData();
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void btnAddPlan_Click(object sender, EventArgs e)
    {
        try
        {
            Session["ResourceAddCheckPlan"] = null;
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;

            if (activeRow == null)
            {
                ShowStatusMessage("请选择设备信息！",false);
                return;
            }

            DataTable dt =ActiveRowToDt(activeRow);
            Session["ResourceAddCheckPlan"] = dt;

            var page = "uMESCheckingPlanPopupForm.aspx";
            var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 1200, 660);

            //   ClientScript.RegisterStartupScript(this.GetType(), btnQR.Text, script);

            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void btnAddTask_Click(object sender, EventArgs e)
    {
        try
        {
            Session["ResourceAddCheckTask"] = null;
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;

            if (activeRow == null)
            {
                ShowStatusMessage("请选择设备信息！", false);
                return;
            }

            DataTable dt = ActiveRowToDt(activeRow);
            Session["ResourceAddCheckTask"] = dt;

            var page = "uMESCheckingTaskPopupForm.aspx";
            var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 1200, 660);

            //   ClientScript.RegisterStartupScript(this.GetType(), btnQR.Text, script);

            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 选择的行转化为dt
    /// </summary>
    /// <param name="activeRow"></param>
    /// <returns></returns>
    DataTable ActiveRowToDt(UltraGridRow activeRow)
    {
        DataTable dt = new DataTable();

        foreach (UltraGridColumn col in ItemGrid.Columns)
        {
            if (dt.Columns.Contains(col.Key))
                continue;
            dt.Columns.Add(col.Key);
        }

        var dr = dt.NewRow();
        foreach (UltraGridColumn col in ItemGrid.Columns)
        {
            dr[col.Key] = activeRow.Cells.FromKey(col.Key).Value;
        }
        dt.Rows.Add(dr);

        return dt;
    }

}